<template>
	<div v-loading="loading">
		<AplidForm ref="formRef" v-bind="formConfig" v-model="formModel" @submit="onSubmit" @reset="onReset">
			<template v-slot:configForm>
				<div class="config-box">
					<!-- <NavTabs
						:closable="true"
						:addable="!userInfo.authArea ? true : false"
						:max="4"
						:tabs="tabsList"
						v-model="activeIndex"
						@tab-delete="handleTabDelete"
						@tab-change="handleTabsClick"
						@tab-add="handleTabsAdd"
					></NavTabs> -->
					<div class="area-config">
						<div class="text-label">适用范围</div>
						<div class="text-value">
							<AreaPanel v-if="!loading" v-model="configList[activeIndex].adaptRangeJsonArray" :areaSchemeList="areaSchemeList"></AreaPanel>
						</div>
					</div>
				</div>
				<el-scrollbar max-height="30rem" class="w-100 mt10">
					<draggable v-model="configList[activeIndex].nodeList" tag="ul" class="config-box" group="people" item-key="index">
						<template #item="{ element, index }">
							<li>
								<div class="config-item">
									<div class="card-header f-between">
										<span class="index-box fc">{{ index + 1 }}</span>
										<div class="tc mt10 footer-btn" v-if="configList[activeIndex].nodeList.length - 1 == index">
											<el-button class="button" v-if="index !== 0" @click="handleDelete()">删除</el-button>
											<el-button type="primary" class="button mt10" @click="handleAdd">
												<el-icon>
													<icon-plus />
												</el-icon>
												审批环节
											</el-button>
										</div>
									</div>
									<div class="flex mt10">
										<p class="label">审批层级</p>
										<el-radio-group v-model="element.approvalHierarchy">
											<el-radio-button label="所属社区" value="1"></el-radio-button>
											<el-radio-button label="所属街道" value="2"></el-radio-button>
											<el-radio-button label="所属区" value="3"></el-radio-button>
											<el-radio-button label="市级" value="4"></el-radio-button>
											<el-radio-button label="第三方" value="5"></el-radio-button>
										</el-radio-group>
									</div>
									<Associate v-show="element.approvalHierarchy == 5" v-model:userList="element.userList" v-model="element.userIdList"></Associate>
									<div class="flex mt10">
										<p class="label">审批方式</p>
										<el-radio-group v-model="element.approvalWay">
											<el-radio-button :value="1" label="或签（一人签署则审批通过）"></el-radio-button>
											<el-radio-button :value="2" label="会签（全部签署则审批通过）"></el-radio-button>
										</el-radio-group>
									</div>
									<div class="flex mt10">
										<p class="label">驳回层级</p>
										<el-radio-group v-model="element.rejectHierarchy">
											<el-radio-button :value="1" label="驳回至数据提交方"></el-radio-button>
											<el-radio-button :value="2" label="驳回至上级" v-if="index > 0"></el-radio-button>
										</el-radio-group>
									</div>
								</div>
								<div class="down-arrow fc" v-if="nodeList.length - 1 !== index">
									<img :src="downArrowImg" alt="" class="img" />
								</div>
							</li>
						</template>
					</draggable>
				</el-scrollbar>
			</template>
		</AplidForm>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod'
import draggable from 'vuedraggable'
import { api, formConfig } from '../config'
import Associate from './Associate/index.vue'
import { getStore } from '@/utils/store'
import downArrowImg from '@/assets/icons/down-arrow.png'
import NavTabs from '../NavTabs/index.vue'
// import NavTabs from '@/views/instOperate/components/NavTabs/index.vue'
import AreaPanel from './AreaPanel/index.vue'
import { uniqueId } from 'lodash-es'
type Props = {
	nowRowData: any
	approvalConfigId?: string | number
}
const props = withDefaults(defineProps<Props>(), {})
const emit = defineEmits(['refresh'])
const loading = ref(true)
const userInfo = getStore('userInfo')
const authAreaLen = [userInfo.authProvince, userInfo.authCity, userInfo.authArea, userInfo.authStreet, userInfo.authCommunity].filter(Boolean).length
let approvalNum = '4'
switch (authAreaLen) {
	case 1:
		approvalNum = '5'
		break
	case 2:
		approvalNum = '4'
		break
	case 3:
		approvalNum = '3'
		break
	case 4:
		approvalNum = '2'
		break
	case 5:
		approvalNum = '1'
		break
	default:
		break
}

const configList: any = ref({
	0: {
		label: `方案 1`,
		adaptRangeJsonArray: [],
		nodeList: [
			{
				approvalHierarchy: approvalNum,
				approvalWay: 1,
				rejectHierarchy: 1,
			},
		],
	},
})
// 所有选择的适用范围
const areaSchemeList = computed(() => {
	return Object.values(configList.value)
		.map((item: any) => {
			return item.adaptRangeJsonArray.map((item) => item.value).join(',')
		})
		.join(',')
})

const nodeList = ref(
	props.nowRowData.workflowConfiguration || [
		{
			approvalHierarchy: approvalNum,
			approvalWay: 1,
			rejectHierarchy: 1,
		},
	]
)
const formModel: any = ref({
	userIdList: '',
	...props.nowRowData,
	adaptRangeJsonArray: [],
})

const activeIndex: any = ref(0)
const tabsList: any = ref([
	{
		label: '方案1',
		value: '0',
	},
])
const handleTabsClick = (item) => {
	// activeIndex.value = item.value
	console.log(configList.value, 'configList------')
}

const renderConfigList = (type) => {
	let item = tabsList.value[tabsList.value.length - 1]
	activeIndex.value = item.value

	if (type == 'delete') return
	configList.value[item.value] = {
		label: `方案 ${item.value}`,
		adaptRangeJsonArray: [],
		nodeList: [
			{
				approvalHierarchy: approvalNum,
				approvalWay: 1,
				rejectHierarchy: 1,
			},
		],
	}
}

const handleTabsAdd = (active) => {
	tabsList.value.push({
		label: `方案 ${active}`,
		value: uniqueId('audit_'),
	})
	renderConfigList('add')
}
const handleTabDelete = (item, index) => {
	tabsList.value.splice(index, 1)
	delete configList.value[item.value]
	renderConfigList('delete')
}
const handleDelete = (index?: number) => {
	if (configList.value[activeIndex.value].nodeList.length > 1) {
		if (index) {
			configList.value[activeIndex.value].nodeList.splice(index, 1)
		} else {
			configList.value[activeIndex.value].nodeList.pop()
		}
	}
}
const handleAdd = (index) => {
	configList.value[activeIndex.value].nodeList.push({
		approvalHierarchy: approvalNum,
		approvalWay: 1,
		rejectHierarchy: 1,
	})
}
const onSubmit = (form, done) => {
	const ofsWorkflowSchemeList = Object.keys(configList.value)
		.map((key) => {
			const tempItem = configList.value[key] || {}
			if (tempItem.adaptRangeJsonArray.length > 0 && tempItem.nodeList.length > 0) {
				return {
					workflowName: form.workflowName,
					scheme: `方案 ${+key + 1}`,
					workflowConfiguration: tempItem.nodeList.map((item, index) => {
						return {
							...item,
							sequence: index + 1,
						}
					}),
					adaptRange: tempItem.adaptRangeJsonArray.map((item) => item.value).join(','),
					adaptRangeJsonArray: JSON.stringify(tempItem.adaptRangeJsonArray),
				}
			}
		})
		.filter(Boolean)

	const params = {
		id: formModel.value.workflowId || props.nowRowData.id,
		randomNo: formModel.value.randomNo || props.nowRowData.randomNo,
		subsidyType: form.subsidyType,
		subsidyTypeLabel: form.subsidyTypeLabel,
		workflowName: form.workflowName,
		cycle: form.cycle,
		ofsWorkflowSchemeList,
	}
	const baseApi = form.id ? api.edit : api.add
	apiMod[baseApi]({
		...params,
	})
		.then((res) => {
			ElMessage.success('操作成功')
			emit('refresh', res.data)
			done()
		})
		.catch((err) => {
			done()
		})
}

const getDetail = () => {
	if (!props.approvalConfigId) {
		loading.value = false
		return
	}
	loading.value = true
	apiMod
		.view_ofsWorkflowScheme_acquire({
			randomNo: props.approvalConfigId || props.nowRowData.randomNo,
		})
		.then((res) => {
			loading.value = false
			const data = res.data || []
			if (data.length <= 0) return
			let configObj = {}
			tabsList.value = data.map((item, index) => {
				if (index == 0) {
					activeIndex.value = `${index}`
					formModel.value.randomNo = item.randomNo
					formModel.value.workflowName = item.workflowName
					formModel.value.cycle = item.cycle
					formModel.value.workflowId = item.workflowId
				}
				const adaptRange = item.adaptRangeJsonArray ? JSON.parse(item.adaptRangeJsonArray) : []
				configObj[`${index}`] = {
					label: item.scheme,
					value: `${index}`,
					adaptRangeJsonArray: adaptRange,
					nodeList: JSON.parse(item.workflowConfiguration),
				}
				return {
					label: item.scheme,
					value: `${index}`,
				}
			})
			configList.value = configObj
		})
		.catch(() => {
			loading.value = false
		})
}

const onReset = () => {
  emit('refresh')
}
onMounted(() => {
	getDetail()
})
</script>

<style scoped lang="scss">
:deep(.el-radio-group) {
	gap: 10px;
}
:deep(.el-radio-button--default .el-radio-button__inner) {
	background: #e7e7e7;
	border: none;
	border-radius: 6px;
	padding: 4px 16px;
}
:deep(.el-radio-button:first-child .el-radio-button__inner) {
	border-radius: 6px;
}
:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
	background: #6498ff;
	border: none;
	box-shadow: none;
}
:deep(.el-radio-button__inner:hover) {
	color: #fff;
}

.text-label {
	min-width: vw(65);
	margin-right: 20px;
	font-family: 'Microsoft YaHei';
	font-weight: 400;
	font-size: 16px;
	color: #1c1c28;
}
.area-config {
	margin-top: 30px;
}
.config-box {
	margin: 0 auto;
	width: vw(476);
	position: relative;

	.down-arrow {
		padding: 10px 0;
		.img {
			width: 18.55px;
			height: 33px;
			background: transparent;
			transition: transform 0.3s ease-in-out;
		}
	}
	.config-item {
		border-radius: 10px;
		padding: 10px;
		// box-shadow: var(--el-box-shadow);
		margin-top: 10px;
		border: 1px solid #4787f0;

		.label {
			@extend .text-label;
		}

		.card-header {
			position: relative;
			.index-box {
				width: 24px;
				height: 20px;
				border-radius: 4px;
				background: #4787f0;
				font-family: 'Microsoft YaHei Bold';
				font-weight: 700;
				font-size: 14px;
				color: #feffff;
			}
			.footer-btn {
				position: absolute;
				top: 0;
				right: -170px;
				display: flex;
				flex-flow: column;
				align-items: baseline;
			}
		}
	}
}
</style>
